package com.xinziruo.richclient.util.filecommand.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import com.xinziruo.richclient.util.AssertUtils;
import com.xinziruo.richclient.util.ExceptionUtils;
import com.xinziruo.richclient.util.IOUtils;
import com.xinziruo.richclient.util.filecommand.SelectiveSupportFileCommand;

/**
 * 
 * @author loudyn
 * 
 */
public class ZipUncompressFileCommand extends SelectiveSupportFileCommand {

	private final File target;
	private final File source;
	private final String encoding;

	/**
	 * 
	 * @param source
	 * @param target
	 * @param encoding
	 */
	public ZipUncompressFileCommand(File source, File target, String encoding) {
		this.source = source;
		this.target = target;
		this.encoding = encoding;
	}

	/**
	 * 
	 * @param source
	 * @param target
	 * @param encoding
	 */
	public ZipUncompressFileCommand(String source, String target, String encoding) {
		this(new File(source), new File(target), encoding);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.youboy.module.util.filecommand.SelectiveSupportFileCommand#doExecuteWhenSupport()
	 */
	@Override
	protected void executeWhenSupport() {
		doInternalArchive(source, target, encoding);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.youboy.module.util.filecommand.SelectiveSupportFileCommand#support()
	 */
	@Override
	protected boolean support() {
		AssertUtils.notNull(source, "source must not be null!");

		if (StringUtils.isBlank(source.getName())) {
			return false;
		}
		
		return source.getName().endsWith(".zip");
	}

	private void doInternalArchive(File source, File target, String encoding) {
		try {

			ZipFile sourceAsZip = new ZipFile(source, encoding);

			for (Enumeration<ZipArchiveEntry> entries = sourceAsZip
					.getEntries(); entries.hasMoreElements();) {

				ZipArchiveEntry entry = entries.nextElement();

				if (entry.isDirectory()) {
					FileUtils.forceMkdir(new File(target, entry.getName()));
				}

				else {

					InputStream in = null;
					OutputStream out = null;

					try {

						in = sourceAsZip.getInputStream(entry);
						out = new FileOutputStream(new File(target, entry.getName()));
						IOUtils.piping(in, out);

					} catch (Exception e) {
						IOUtils.freeQuietly(in, out);
					}

				}

			}

		} catch (Exception e) {
			throw ExceptionUtils.toUnchecked(e);
		}

	}

}
